package net.cjw.initsb.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import net.cjw.initsb.common.ServiceResult;
import net.cjw.initsb.service.FileServiceI;
import net.cjw.initsb.utils.DateUtil;

@Service
@Transactional
public class FileServiceImpl implements FileServiceI {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${file.save.path}")
	private String fileSavePath;

	@Override
	public ServiceResult<String> uploadOneFile(MultipartFile file) {
		// 获取文件名
		String fileName = file.getOriginalFilename();
		logger.info("上传的文件名为：" + fileName);
		// 获取文件的后缀名
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		logger.info("上传的后缀名为：" + suffixName);
		// 文件上传后的路径
		String filePath = fileSavePath;// "G:/opt/file/";
		String dateFilePath = DateUtil.format(new Date(), DateUtil.DATE_FORMAT);
		// 解决中文问题，liunx下中文路径，图片显示问题
		fileName = dateFilePath + "_" + UUID.randomUUID() + suffixName;
		File dest = new File(filePath + dateFilePath + File.separator + fileName);
		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest);
			return ServiceResult.buildSuccess("/file/image/" + fileName);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ServiceResult.buildError("上传失败");
	}

	@Override
	public ServiceResult<String> uploadMoreFile(List<MultipartFile> files) {
		MultipartFile file = null;
		for (int i = 0; i < files.size(); ++i) {
			file = files.get(i);
			if (file.isEmpty()) {
				continue;
			}
			// 获取文件名
			String fileName = file.getOriginalFilename();

			logger.info("上传的文件名为：" + fileName);
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));
			logger.info("上传的后缀名为：" + suffixName);
			// 文件上传后的路径
			String filePath = fileSavePath;// "G:/opt/files/";
			String dateFilePath = DateUtil.format(new Date(), DateUtil.DATE_FORMAT);
			// 解决中文问题，liunx下中文路径，图片显示问题
			fileName = dateFilePath + "_" + UUID.randomUUID() + suffixName;
			File dest = new File(filePath + dateFilePath + File.separator + fileName);
			// 检测是否存在目录
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}
			try {
				file.transferTo(dest);
				continue;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ServiceResult.buildSuccess();
	}

}